import config from '../../config/api.js';
	
<template>
	<view class="container">
		
		<!-- 搜索框 -->
		<view class="search-box">
			<input 
				type="text" 
				placeholder="搜索菜品" 
				class="search-input"
				v-model="searchKeyword"
			/>
		</view>
		
		<!-- 主体内容 -->
		<view class="main-content">
			<!-- 左侧分类 -->
			<scroll-view class="category-list" scroll-y="true">
				<view 
					v-for="(category, index) in categories" 
					:key="index"
					:class="['category-item', currentCategoryIndex === index ? 'active' : '']"
					@click="switchCategory(index)"
					v-if="categories"
				>
					<image 
						:src="category.icon" 
						class="category-icon" 
						v-if="category.icon"
					></image>
					<text class="category-name">{{ category.name }}</text>
					<text 
						v-if="getCategoryItemCount(category.id) > 0" 
						class="category-badge"
					>
						{{ getCategoryItemCount(category.id) }}
					</text>
				</view>
			</scroll-view>
			
			<!-- 右侧菜品 -->
			<scroll-view class="dish-list" scroll-y="true">
				<view 
					v-for="dish in filteredDishes" 
					:key="dish.id"
					class="dish-item"
					v-if="filteredDishes"
				>
					<image 
						:src="dish.image" 
						class="dish-image" 
						mode="aspectFill"
						v-if="dish.image"
					></image>
					<view class="dish-info">
						<view class="dish-header">
							<text class="dish-name">{{ dish.name }}</text>
							<text class="dish-sales">月售{{ dish.sales }}份</text>
						</view>
						<text class="dish-description">{{ dish.description }}</text>
						<view class="dish-footer">
							<text class="dish-price">¥{{ dish.price }}</text>
							<view class="dish-actions">
								<view 
									class="action-btn reduce-btn"
									@click="reduceDish(dish)"
									v-if="getDishCount(dish.id) > 0"
								>
									-
								</view>
								<text 
									class="dish-count"
									v-if="getDishCount(dish.id) > 0"
								>
									{{ getDishCount(dish.id) }}
								</text>
								<view 
									class="action-btn add-btn"
									@click="addDish(dish)"
								>
									+
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 空状态 -->
				<view v-if="!filteredDishes || filteredDishes.length === 0" class="empty-state">
					<text>暂无相关菜品</text>
				</view>
			</scroll-view>
		</view>
		
		<!-- 购物车 -->
		<view class="cart-bar" v-if="cartItems && cartItems.length > 0">
			<view class="cart-summary">
				<text class="cart-total">¥{{ cartTotalPrice }}</text>
				<text class="cart-count">{{ cartTotalCount }}个菜品</text>
			</view>
			<button class="checkout-btn" @click="checkout">去结算</button>
		</view>
		
		<!-- 备注弹窗 -->
		<view class="popup-overlay" v-if="showRemarkPopup" @click="closeRemarkPopup">
			<view class="popup-content" @click.stop>
				<view class="popup-header">
					<text class="popup-title">添加备注</text>
					<text class="close-btn" @click="closeRemarkPopup">×</text>
				</view>
				<view class="remark-inputs">
					<input 
						type="text" 
						placeholder="请输入特殊要求" 
						class="remark-input"
						v-model="currentRemark"
					/>
					<view class="remark-tags">
						<view 
							v-for="(tag, index) in remarkTags" 
							:key="index"
							:class="['remark-tag', currentRemarks && currentRemarks.includes(tag) ? 'selected' : '']"
							@click="toggleRemarkTag(tag)"
							v-if="remarkTags"
						>
							{{ tag }}
						</view>
					</view>
				</view>
				<view class="popup-footer">
					<button class="cancel-btn" @click="closeRemarkPopup">取消</button>
					<button class="confirm-btn" @click="confirmRemark">确定</button>
				</view>
			</view>
		</view>
		
		<!-- 餐次选择弹窗 -->
		<view class="popup-overlay" v-if="showMealTypePopup" @click="closeMealTypePopup">
			<view class="popup-content" @click.stop>
				<view class="popup-header">
					<text class="popup-title">选择餐次</text>
					<text class="close-btn" @click="closeMealTypePopup">×</text>
				</view>
				<view class="meal-type-options">
					<view 
						class="meal-type-option"
						:class="{ selected: selectedMealType === '午餐' }"
						@click="selectedMealType = '午餐'"
					>
						午餐
					</view>
					<view 
						class="meal-type-option"
						:class="{ selected: selectedMealType === '晚餐' }"
						@click="selectedMealType = '晚餐'"
					>
						晚餐
					</view>
				</view>
				<view class="popup-footer">
					<button class="cancel-btn" @click="closeMealTypePopup">取消</button>
					<button class="confirm-btn" @click="confirmMealType">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '../../config/api.js';
	
	export default {
		data() {
			return {
				title: '家庭点餐',
				searchKeyword: '',
				currentCategoryIndex: 0,
				showRemarkPopup: false,
				showMealTypePopup: false,
				selectedMealType: '',
				currentDish: null,
				currentRemark: '',
				currentRemarks: [],
				
				// 分类数据（从API获取）
				categories: [],
				
				// 菜品数据（从API获取）
				dishes: [],
				
				// 购物车数据
				cartItems: [],
				
				// 备注标签
				remarkTags: ['少冰', '去冰', '少糖', '去葱', '去香菜', '加辣', '不辣', '打包']
			}
		},
		onLoad() {
			// 页面加载时获取菜品分类和菜品数据
			this.loadDishCategories();
			this.loadDishes();
		},
		methods: {
			// 加载菜品分类
			async loadDishCategories() {
				try {
					const res = await uni.request({
						url: config.baseUrl + config.api.dishCategories,
						method: 'GET'
					});
					
					if (res.statusCode === 200 && res.data && Array.isArray(res.data.data.categories)) {
						this.categories = res.data.data.categories;
						
						// 如果没有默认选中分类，选中第一个
						if (this.categories.length > 0) {
							this.currentCategoryIndex = 0;
						}
					} else {
						console.error('获取菜品分类失败:', res);
						// 使用模拟数据
						this.loadMockCategories();
					}
				} catch (error) {
					console.error('获取菜品分类异常:', error);
				}
			},
			
			// 加载菜品数据
			async loadDishes() {
				try {
					const res = await uni.request({
						url: config.baseUrl + config.api.dishList,
						method: 'GET'
					});
					if (res.statusCode === 200 && res.data && Array.isArray(res.data.data.dishes)) {
						this.dishes = res.data.data.dishes;
						
					} else {
						console.error('获取菜品数据失败:', res);
						// 使用模拟数据
						this.loadMockDishes();
					}
				} catch (error) {
					console.error('获取菜品数据异常:', error);
				}
			},
			
			// 切换分类
			switchCategory(index) {
				this.currentCategoryIndex = index;
			},
			
			// 获取分类下的菜品数量
			getCategoryItemCount(categoryId) {
				if (!this.dishes) return 0;
				return this.dishes.filter(dish => dish.categoryId === categoryId).length;
			},
			
			// 获取菜品在购物车中的数量
			getDishCount(dishId) {
				if (!this.cartItems) return 0;
				const item = this.cartItems.find(item => item.dishId === dishId);
				return item ? item.quantity : 0;
			},
			
			// 添加菜品到购物车
			addDish(dish) {
				this.currentDish = dish;
				this.showRemarkPopup = true;
			},
			
			// 减少菜品数量
			reduceDish(dish) {
				if (!this.cartItems) return;
				const index = this.cartItems.findIndex(item => item.dishId === dish.id);
				if (index !== -1) {
					if (this.cartItems[index].quantity > 1) {
						this.cartItems[index].quantity--;
					} else {
						this.cartItems.splice(index, 1);
					}
				}
			},
			
			// 关闭备注弹窗
			closeRemarkPopup() {
				this.showRemarkPopup = false;
				this.currentRemark = '';
				this.currentRemarks = [];
			},
			
			// 切换备注标签
			toggleRemarkTag(tag) {
				const index = this.currentRemarks.indexOf(tag);
				if (index !== -1) {
					this.currentRemarks.splice(index, 1);
				} else {
					this.currentRemarks.push(tag);
				}
			},
			
			// 确认备注
			confirmRemark() {
				if (this.currentDish) {
					const remarks = this.currentRemarks ? [...this.currentRemarks] : [];
					if (this.currentRemark) {
						remarks.push(this.currentRemark);
					}
					
					const remarkStr = remarks.join(',');
					
					if (!this.cartItems) {
						this.cartItems = [];
					}
					
					const index = this.cartItems.findIndex(item => 
						item.dishId === this.currentDish.id && item.remarks === remarkStr
					);
					
					if (index !== -1) {
						this.cartItems[index].quantity++;
					} else {
						this.cartItems.push({
							dishId: this.currentDish.id,
							name: this.currentDish.name,
							price: this.currentDish.price,
							quantity: 1,
							remarks: remarkStr
						});
					}
				}
				
				this.closeRemarkPopup();
			},
			
			// 选择餐次
			selectMealType(type) {
				this.selectedMealType = type;
			},
			
			// 去结算
			checkout() {
				// 显示选择餐次的弹窗
				this.showMealTypePopup = true;
			},
			
			// 确认餐次
			confirmMealType() {
				if (!this.selectedMealType) {
					uni.showToast({
						title: '请选择餐次',
						icon: 'none'
					});
					return;
				}
				
				// 保存待做的菜品到本地存储
				this.savePendingTasks();
				
				// 关闭弹窗
				this.showMealTypePopup = false;
				
				// 清空购物车
				this.cartItems = [];
				
				uni.showToast({
					title: '点餐成功',
					icon: 'success'
				});
			},
			
			// 保存待做的菜品
			savePendingTasks() {
				try {
					// 获取现有的待做菜品
					let pendingTasks = uni.getStorageSync('pendingTasks') || [];
					
					// 添加当前购物车中的菜品
					const cartItems = this.cartItems || [];
					const newTasks = cartItems.map(item => {
						return {
							dishName: item.name,
							quantity: item.quantity,
							remarks: item.remarks,
							mealType: this.selectedMealType,
							time: this.getCurrentTime()
						};
					});
					
					// 合并到现有任务中
					pendingTasks = pendingTasks.concat(newTasks);
					
					// 保存到本地存储
					uni.setStorageSync('pendingTasks', pendingTasks);
					
					// 重置选择
					this.selectedMealType = '';
				} catch (e) {
					console.error('保存待做菜品失败', e);
				}
			},
			
			// 获取当前时间
			getCurrentTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},
			
			// 关闭餐次选择弹窗
			closeMealTypePopup() {
				this.showMealTypePopup = false;
				this.selectedMealType = '';
			}
		},
		computed: {
			// 过滤后的菜品
			
			filteredDishes() {
				if (!this.categories || this.categories.length === 0 || !this.dishes) {
					return [];
				}
				const currentCategoryId = this.categories[this.currentCategoryIndex]?.id;
				
				if (!currentCategoryId) {
					return [];
				}
				
				const filtered = this.dishes.filter(dish => {
					if (dish.category_id === currentCategoryId) {
						return true;
					} 
				});
				return filtered;
			},
			// 购物车总价
			cartTotalPrice() {
				if (!this.cartItems) return 0;
				return this.cartItems.reduce((total, item) => {
					return total + (item.price * item.quantity);
				}, 0).toFixed(2);
			},
			// 购物车总数量
			cartTotalCount() {
				if (!this.cartItems) return 0;
				return this.cartItems.reduce((total, item) => {
					return total + item.quantity;
				}, 0);
			}
		}
	}
</script>

<style scoped>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
	}
	
	.navbar {
		height: 88rpx;
		background-color: #f0ad4e;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}
	
	.nav-title {
		color: white;
		font-size: 36rpx;
		font-weight: bold;
	}
	
	.search-box {
		padding: 20rpx;
		background-color: white;
	}
	
	.search-input {
		height: 60rpx;
		background-color: #f5f5f5;
		border-radius: 30rpx;
		padding: 0 30rpx;
		font-size: 28rpx;
	}
	
	.main-content {
		flex: 1;
		display: flex;
		flex-direction: row;
		overflow: hidden;
	}
	
	.category-list {
		width: 200rpx;
		background-color: #f8f8f8;
	}
	
	.category-item {
		height: 100rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		position: relative;
		border-bottom: 1rpx solid #eee;
	}
	
	.category-item.active {
		background-color: white;
		font-weight: bold;
		color: #f0ad4e;
	}
	
	.category-icon {
		width: 40rpx;
		height: 40rpx;
		margin-bottom: 10rpx;
	}
	
	.category-name {
		font-size: 26rpx;
		color: #333;
	}
	
	.category-badge {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		background-color: #f0ad4e;
		color: white;
		font-size: 20rpx;
		border-radius: 50%;
		width: 30rpx;
		height: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.dish-list {
		flex: 1;
		padding: 20rpx;
	}
	
	.dish-item {
		background-color: white;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		padding: 20rpx;
		display: flex;
		flex-direction: row;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	}
	
	.dish-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 10rpx;
		margin-right: 20rpx;
	}
	
	.dish-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}
	
	.dish-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10rpx;
	}
	
	.dish-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.dish-sales {
		font-size: 24rpx;
		color: #999;
	}
	
	.dish-description {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 20rpx;
		flex: 1;
	}
	
	.dish-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.dish-price {
		font-size: 32rpx;
		color: #f0ad4e;
		font-weight: bold;
	}
	
	.dish-actions {
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	
	.action-btn {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		font-weight: bold;
	}
	
	.reduce-btn {
		background-color: #f5f5f5;
		color: #666;
	}
	
	.add-btn {
		background-color: #f0ad4e;
		color: white;
	}
	
	.dish-count {
		margin: 0 15rpx;
		font-size: 28rpx;
		color: #333;
	}
	
	.empty-state {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.cart-bar {
		height: 100rpx;
		background-color: #333;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx;
	}
	
	.cart-summary {
		display: flex;
		flex-direction: column;
	}
	
	.cart-total {
		font-size: 36rpx;
		color: white;
		font-weight: bold;
	}
	
	.cart-count {
		font-size: 24rpx;
		color: #ccc;
	}
	
	.checkout-btn {
		background-color: #f0ad4e;
		color: white;
		border: none;
		border-radius: 50rpx;
		width: 180rpx;
		height: 70rpx;
		font-size: 30rpx;
	}
	
	.popup-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0,0,0,0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}
	
	.popup-content {
		background-color: white;
		width: 80%;
		border-radius: 20rpx;
		overflow: hidden;
	}
	
	.popup-header {
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #eee;
	}
	
	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.close-btn {
		font-size: 40rpx;
		color: #999;
	}
	
	.remark-inputs {
		padding: 30rpx;
	}
	
	.remark-input {
		height: 70rpx;
		border: 1rpx solid #eee;
		border-radius: 10rpx;
		padding: 0 20rpx;
		margin-bottom: 30rpx;
		font-size: 28rpx;
	}
	
	.remark-tags {
		display: flex;
		flex-wrap: wrap;
	}
	
	.remark-tag {
		padding: 15rpx 25rpx;
		background-color: #f5f5f5;
		border-radius: 30rpx;
		font-size: 26rpx;
		color: #666;
		margin: 0 15rpx 15rpx 0;
	}
	
	.remark-tag.selected {
		background-color: #f0ad4e;
		color: white;
	}
	
	.popup-footer {
		display: flex;
		flex-direction: row;
		border-top: 1rpx solid #eee;
	}
	
	.cancel-btn, .confirm-btn {
		flex: 1;
		height: 80rpx;
		border: none;
		border-radius: 0;
		font-size: 30rpx;
	}
	
	.cancel-btn {
		background-color: #f5f5f5;
		color: #666;
	}
	
	.confirm-btn {
		background-color: #f0ad4e;
		color: white;
	}
	
	.meal-type-options {
		padding: 30rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
	}
	
	.meal-type-option {
		padding: 20rpx 40rpx;
		border: 1rpx solid #eee;
		border-radius: 10rpx;
		font-size: 32rpx;
		color: #333;
	}
	
	.meal-type-option.selected {
		background-color: #f0ad4e;
		color: white;
		border-color: #f0ad4e;
	}
</style>